﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using DataAccess;
using com.chttl.ienc.bean;
using java.util;
using Microsoft.Reporting.WebForms;
using System.IO;
using Ionic.Zip;

namespace iEN.Report
{
    public partial class MonthlyReport : System.Web.UI.Page
    {
        //初始頁面
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)//先判斷是否已經登入過
            {
                if (Session["LoginName"] == null)
                {
                    Response.Write("<script>alert('請先登入！！');location.href='../Login.aspx';</script>");
                }

                //權限判斷
                //Operator : 可查詢、匯出、列印報表。   Session["SysAdmin"]=1
                //Director : 管理者，可使用所有功能。   Session["SysAdmin"]=2
                string sSysAdmin = Session["SysAdmin"].ToString();
                if (sSysAdmin != "1" && sSysAdmin != "2")
                {
                    ErrorMsg("您沒有使用此頁面的權限，請聯絡系統管理員！");
                    btnQuery.Visible = false;
                    return;
                }

                tbBgnDate.Text = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("yyyy/MM/dd");
                DateTime dtNextMonthFirstDay = new DateTime(DateTime.Now.Year, DateTime.Now.AddMonths(1).Month, 1);
                tbEndDate.Text = new DateTime(DateTime.Now.Year, DateTime.Now.Month, dtNextMonthFirstDay.AddDays(-1).Day).ToString("yyyy/MM/dd");
                Session["FolderName"] = Session.SessionID.ToString();
                Intialize();    //初始化控制項
            }
        }

        /// <summary>
        /// 初始化控制項
        /// </summary>
        private void Intialize()
        {
            //取得大樓名稱
            ddlBuilding.Items.Clear();
            ddlBuilding.Items.Add("---");
            DataTable dtOrgGroup = new DBAccess().getOrgGroupTableByLevel(1);  //取得Level=1的大樓資訊
            for (int i = 0; i < dtOrgGroup.Rows.Count; i++)
            {
                ListItem li = new ListItem(dtOrgGroup.Rows[i]["_name"].ToString().Trim(), dtOrgGroup.Rows[i]["_id"].ToString());
                ddlBuilding.Items.Add(li);
            }
            ddlBuilding.SelectedIndex = 0;

            btnQuery.Attributes["onclick"] = ";document.getElementById('Loading').style.visibility='visible';";
        }

        /// <summary>
        /// 重新選擇大樓
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlBuilding_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlFloor.Items.Clear();
            ddlFloor.Items.Add("---");
            if (ddlBuilding.SelectedItem.Text != "---")
            {
                string sID = ddlBuilding.SelectedItem.Value;
                DataTable dtOrgGroup = new DBAccess().getOrgGroupTableByLevel(2);  //取得Level=2的樓層資訊
                dtOrgGroup.DefaultView.Sort = " _name";
                dtOrgGroup = dtOrgGroup.DefaultView.ToTable();

                IEnumerable<DataRow> query = from r in dtOrgGroup.AsEnumerable()
                                             where sID.Contains(r.Field<Int32>("_parent_id").ToString())
                                             select r;
                foreach (DataRow r in query)
                {
                    ListItem li = new ListItem(r["_name"].ToString().Trim(), r["_id"].ToString());
                    ddlFloor.Items.Add(li);
                }
            }
            UpdatePanel3.Visible = false;
        }

        /// <summary>
        /// 重新選擇樓層
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlFloor_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlRoom.Items.Clear();
            ddlRoom.Items.Add("---");
            if (ddlFloor.SelectedItem.Text != "---")
            {
                string sID = ddlFloor.SelectedItem.Value;
                DataTable dtOrgGroup = new DBAccess().getOrgGroupTableByLevel(3);  //取得Level=3的寢室資訊
                dtOrgGroup.DefaultView.Sort = " _name";
                dtOrgGroup = dtOrgGroup.DefaultView.ToTable();

                IEnumerable<DataRow> query = from r in dtOrgGroup.AsEnumerable()
                                             where sID.Contains(r.Field<Int32>("_parent_id").ToString())
                                             select r;
                foreach (DataRow r in query)
                {
                    ListItem li = new ListItem(r["_name"].ToString().Trim(), r["_id"].ToString());
                    ddlRoom.Items.Add(li);
                }
            }
            UpdatePanel3.Visible = false;
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                lblStatus.Text = "";
                if (ddlBuilding.SelectedItem.Text == "---")
                {
                    ErrorMsg("請選擇欲查詢的大樓！"); 
                    return;
                }

                if (ddlBuilding.SelectedItem.Text != "---" && ddlFloor.SelectedItem.Text == "---")  //大樓用電月報表
                {
                    int iBuilding = Convert.ToInt32(ddlBuilding.SelectedItem.Value);
                    BuildingMonthlyReport(iBuilding);
                }
                else if (ddlFloor.SelectedItem.Text != "---" && ddlRoom.SelectedItem.Text == "---")  //樓層用電月報表
                {
                    int iFloor = Convert.ToInt32(ddlFloor.SelectedItem.Value);
                    FloorMonthlyReport(iFloor);
                }
                else if (ddlRoom.SelectedItem.Text != "---")    //寢室用電月報表
                {
                    int iRoom = Convert.ToInt32(ddlRoom.SelectedItem.Value);
                    RoomMonthlyReport(iRoom);
                }

                ScriptManager.RegisterStartupScript(this, this.GetType(), "HideLoading", ";document.getElementById('Loading').style.visibility='hidden';", true);
            }
            catch (Exception ex)
            {
                lblStatus.Text += ex.Message;
                UpdatePanel3.Visible = false;
            }
        }

        private void RoomMonthlyReport(int iRoom)
        {
            string sBuildingName = ddlBuilding.SelectedItem.Text;   //大樓名稱
            string sBgnDate = tbBgnDate.Text;
            string sEndDate = tbEndDate.Text;
            DateTime dtBgnDate = DateTime.Parse(sBgnDate);
            DateTime dtEndDate = DateTime.Parse(sEndDate);
            string sRoom = ddlRoom.SelectedItem.Text;

            if (dtBgnDate > dtEndDate)
            {
                ErrorMsg("查詢的起始時間需大於結束時間！");
                return;
            }

            //查寢室電錶
            int iElectricMeter = new DBAccess().getElectricMeterByRoom(iRoom);
            if (iElectricMeter != -1)
            {
                decimal dTotalPower = 0;
                Int32 iTotalMoney = 0;
                iEN.Report.ReportDesign.StaticReportDataSet StaticReportDataSet = new ReportDesign.StaticReportDataSet();
                for (int iDay = 0; iDay < (dtEndDate - dtBgnDate).TotalDays + 1; iDay++)
                {
                    //查用電資料
                    string sDate = dtBgnDate.AddDays(iDay).ToString("yyyy/MM/dd");
                    DataTable dt = new DBAccess().getTag_etldataTableByTagID(iElectricMeter, DateTime.Parse(sDate));
                    if (dt!=null && dt.Rows.Count >= 2)
                    {
                        double dBgnRecord = Convert.ToDouble(dt.Rows[0]["_last"].ToString());                   //該日第一筆資料
                        double dEndRecord = Convert.ToDouble(dt.Rows[dt.Rows.Count - 1]["_last"].ToString());   //該日最後一筆資料

                        iEN.Report.ReportDesign.StaticReportDataSet.l_tag_etldataRow TempRow = (iEN.Report.ReportDesign.StaticReportDataSet.l_tag_etldataRow)(StaticReportDataSet.l_tag_etldata.NewRow());
                        TempRow._start_time = Convert.ToDateTime(dt.Rows[dt.Rows.Count - 1]["_start_time"].ToString());
                        TempRow._end_time = Convert.ToDateTime(dt.Rows[dt.Rows.Count - 1]["_end_time"].ToString());
                        TempRow._first = Convert.ToDouble(dt.Rows[dt.Rows.Count - 1]["_first"].ToString());
                        TempRow._last = dEndRecord;
                        decimal dPowerCount = (decimal)dEndRecord - (decimal)dBgnRecord;
                        TempRow._average = String.Format("{0:0.####}", dPowerCount);                                                        //_average作為使用電度數(度)
                        dTotalPower += dPowerCount;
                        TempRow._id = Convert.ToInt32(dt.Rows[dt.Rows.Count - 1]["_id"].ToString());
                        TempRow._datetime = DateTime.Parse(dt.Rows[dt.Rows.Count - 1]["_start_time"].ToString()).ToString("yyyy/MM/dd");    //_start_time作為資料時間
                        TempRow._device_id = Convert.ToInt32(dt.Rows[dt.Rows.Count - 1]["_device_id"].ToString());
                        TempRow._tag_id = Convert.ToInt32(dt.Rows[dt.Rows.Count - 1]["_tag_id"].ToString());
                        string sMoney = String.Format("{0:0}", (dPowerCount * 4) > 0 ? (dPowerCount * 4) : 0);
                        TempRow._count = sMoney;                                                                                            //_count作為金額
                        iTotalMoney += Convert.ToInt32(sMoney);
                        StaticReportDataSet.l_tag_etldata.Addl_tag_etldataRow(TempRow);
                    }
                }

                if (StaticReportDataSet.l_tag_etldata.Rows.Count > 0)
                {
                    ReportViewer1.Reset();
                    ReportViewer1.LocalReport.DataSources.Clear();
                    ReportViewer1.LocalReport.ReportPath = "Report\\ReportDesign\\MonthlyReport.rdlc";
                    ReportViewer1.LocalReport.SetParameters(QueryReportParameter(
                        "查詢日期:" + sBgnDate + "~" + sEndDate,
                        sBuildingName + "用電月報表",
                        sRoom,
                        String.Format("{0:0.####}", dTotalPower),
                        String.Format("{0:0}", iTotalMoney),
                        "日期時間"
                        ));
                    ReportViewer1.LocalReport.DataSources.Add(new ReportDataSource("ienc_customer_ncku1DataSet", (DataTable)StaticReportDataSet.l_tag_etldata));
                    ReportViewer1.LocalReport.DisplayName = "用電月報表";
                    UpdatePanel3.Visible = true;
                }
                else
                {
                    UpdatePanel3.Visible = false;
                    ErrorMsg("該寢室查無資料，請檢視資料！");
                    return;
                }
            }
            else
            {
                UpdatePanel3.Visible = false;
                ErrorMsg("該寢室查無電錶資料，請檢視資料！");
                return;
            }
        }

        private void RoomMonthlyReport2(int iRoom)
        {
            string sBuildingName = ddlBuilding.SelectedItem.Text;   //大樓名稱
            string sBgnDate = tbBgnDate.Text;
            string sEndDate = tbEndDate.Text;
            DateTime dtBgnDate = DateTime.Parse(sBgnDate);
            DateTime dtEndDate = DateTime.Parse(sEndDate);
            string sRoom = ddlRoom.SelectedItem.Text;

            if (dtBgnDate > dtEndDate)
            {
                ErrorMsg("查詢的起始時間需大於結束時間！");
                return;
            }

            //查寢室電錶
            int iElectricMeter = new DBAccess().getElectricMeterByRoom(iRoom);
            if (iElectricMeter != -1)
            {
                decimal dTotalPower = 0;
                Int32 iTotalMoney = 0;
                iEN.Report.ReportDesign.StaticReportDataSet StaticReportDataSet = new ReportDesign.StaticReportDataSet();

                DateTime dtDate = dtBgnDate;
                while (dtDate <= dtEndDate)
                {
                    //查用電資料
                    DataTable dtFirst = new DBAccess().getTag_etldataTableFirstRecordOfDayByTagID(iElectricMeter, dtDate);  //第一筆資料
                    DataTable dtLast = new DBAccess().getTag_etldataTableLastRecordOfDayByTagID(iElectricMeter, dtDate);  //最後一筆資料
                    if (dtFirst.Rows.Count == 1 && dtLast.Rows.Count == 1)
                    {
                        double dBgnRecord = Convert.ToDouble(dtFirst.Rows[0]["_last"].ToString());      //該月第一筆資料
                        double dEndRecord = Convert.ToDouble(dtLast.Rows[0]["_last"].ToString());       //該月最後一筆資料

                        iEN.Report.ReportDesign.StaticReportDataSet.l_tag_etldataRow TempRow = (iEN.Report.ReportDesign.StaticReportDataSet.l_tag_etldataRow)(StaticReportDataSet.l_tag_etldata.NewRow());
                        TempRow._start_time = Convert.ToDateTime(dtLast.Rows[0]["_start_time"].ToString());
                        TempRow._end_time = Convert.ToDateTime(dtLast.Rows[0]["_end_time"].ToString());
                        TempRow._first = dBgnRecord;
                        TempRow._last = dEndRecord;
                        decimal dPowerCount = (decimal)dEndRecord - (decimal)dBgnRecord;
                        TempRow._average = String.Format("{0:0.####}", dPowerCount);                                                        //_average作為使用電度數(度)
                        dTotalPower += dPowerCount;
                        TempRow._id = Convert.ToInt32(dtLast.Rows[0]["_id"].ToString());
                        TempRow._datetime = DateTime.Parse(dtLast.Rows[0]["_start_time"].ToString()).ToString("yyyy/MM/dd");                //_start_time作為資料時間
                        TempRow._device_id = Convert.ToInt32(dtLast.Rows[0]["_device_id"].ToString());
                        TempRow._tag_id = Convert.ToInt32(dtLast.Rows[0]["_tag_id"].ToString());
                        string sMoney = String.Format("{0:0}", (dPowerCount * 4) > 0 ? (dPowerCount * 4) : 0);
                        TempRow._count = sMoney;                                                                                            //_count作為金額
                        iTotalMoney += Convert.ToInt32(sMoney);
                        StaticReportDataSet.l_tag_etldata.Addl_tag_etldataRow(TempRow);
                    }

                    dtDate = dtDate.AddDays(1);
                }

                if (StaticReportDataSet.l_tag_etldata.Rows.Count > 0)
                {
                    ReportViewer1.Reset();
                    ReportViewer1.LocalReport.DataSources.Clear();
                    ReportViewer1.LocalReport.ReportPath = "Report\\ReportDesign\\MonthlyReport.rdlc";
                    ReportViewer1.LocalReport.SetParameters(QueryReportParameter(
                        "查詢日期:" + sBgnDate + "~" + sEndDate,
                        sBuildingName + "用電月報表",
                        sRoom,
                        String.Format("{0:0.####}", dTotalPower),
                        String.Format("{0:0}", iTotalMoney),
                        "日期時間"
                        ));
                    ReportViewer1.LocalReport.DataSources.Add(new ReportDataSource("ienc_customer_ncku1DataSet", (DataTable)StaticReportDataSet.l_tag_etldata));
                    UpdatePanel3.Visible = true;
                }
                else
                {
                    UpdatePanel3.Visible = false;
                    ErrorMsg("該寢室查無資料，請檢視資料！");
                    return;
                }
            }
            else
            {
                UpdatePanel3.Visible = false;
                ErrorMsg("該寢室查無電錶資料，請檢視資料！");
                return;
            }
        }

        private void FloorMonthlyReport(int iFloor)
        {
            string sBuildingName = ddlBuilding.SelectedItem.Text;   //大樓名稱
            string sFloor = ddlFloor.SelectedItem.Text;             //樓層
            string sBgnDate = tbBgnDate.Text;
            string sEndDate = tbEndDate.Text;
            DateTime dtBgnDate = DateTime.Parse(sBgnDate);
            DateTime dtEndDate = DateTime.Parse(sEndDate);

            if (dtBgnDate > dtEndDate)
            {
                ErrorMsg("查詢的起始時間需大於結束時間！");
                return;
            }

            //查該樓層的所有寢室
            DataTable dtOrgGroup = new DBAccess().getOrgGroupTableByLevel(3);  //取得Level=3的寢室資訊
            IEnumerable<DataRow> query = from r in dtOrgGroup.AsEnumerable()
                                         where iFloor == r.Field<Int32>("_parent_id")
                                         select r;

            decimal dTotalPower = 0;
            Int32 iTotalMoney = 0;
            iEN.Report.ReportDesign.StaticReportDataSet StaticReportDataSet = new ReportDesign.StaticReportDataSet();
            foreach (DataRow r in query)
            {
                string sRoomName = r["_name"].ToString().Trim();
                int iRoom = Convert.ToInt32(r["_id"].ToString());

                iEN.Report.ReportDesign.StaticReportDataSet.l_tag_etldataRow TempRow = (iEN.Report.ReportDesign.StaticReportDataSet.l_tag_etldataRow)(StaticReportDataSet.l_tag_etldata.NewRow());
                
                //查寢室電錶
                int iElectricMeter = new DBAccess().getElectricMeterByRoom(iRoom);
                if (iElectricMeter != -1)
                {
                    //查用電資料
                    DataTable dtFirst = new DBAccess().getTag_etldataTableFirstRecordOfDayByTagID(iElectricMeter, dtBgnDate);   //當月第一筆資料
                    DataTable dtLast = new DBAccess().getTag_etldataTableLastRecordOfDayByTagID(iElectricMeter, dtEndDate);     //當月最後一筆資料
                    if (dtFirst != null && dtLast != null && dtFirst.Rows.Count == 1 && dtLast.Rows.Count == 1)
                    {
                        double dBgnRecord = Convert.ToDouble(dtFirst.Rows[0]["_last"].ToString());      //該月第一筆資料
                        double dEndRecord = Convert.ToDouble(dtLast.Rows[0]["_last"].ToString());       //該月最後一筆資料
                        decimal dPowerCount = (decimal)dEndRecord - (decimal)dBgnRecord;
                        dTotalPower += dPowerCount;
                        string sMoney = String.Format("{0:0}", (dPowerCount * 4) > 0 ? (dPowerCount * 4) : 0);
                        iTotalMoney += Convert.ToInt32(sMoney);
                        
                        TempRow._start_time = Convert.ToDateTime(dtLast.Rows[0]["_start_time"].ToString());
                        TempRow._end_time = Convert.ToDateTime(dtLast.Rows[0]["_end_time"].ToString());
                        TempRow._first = dBgnRecord;
                        TempRow._last = dEndRecord;
                        TempRow._average = String.Format("{0:0.####}", dPowerCount);                    //_average作為使用電度數(度)
                        TempRow._id = Convert.ToInt32(dtLast.Rows[0]["_id"].ToString());
                        TempRow._datetime = sRoomName;                                                  //_datetime用來表示寢室
                        TempRow._device_id = Convert.ToInt32(dtLast.Rows[0]["_device_id"].ToString());
                        TempRow._tag_id = Convert.ToInt32(dtLast.Rows[0]["_tag_id"].ToString());
                        TempRow._count = sMoney;                                                        //_count作為金額
                    }
                    else
                        TempRow._datetime = sRoomName;
                }
                else    //該寢室查無電錶資料
                {
                    TempRow._datetime = sRoomName;
                }

                StaticReportDataSet.l_tag_etldata.Addl_tag_etldataRow(TempRow);
            }

            if (StaticReportDataSet.l_tag_etldata.Rows.Count > 0)
            {
                ReportViewer1.Reset();
                ReportViewer1.LocalReport.DataSources.Clear();
                ReportViewer1.LocalReport.ReportPath = "Report\\ReportDesign\\MonthlyReport.rdlc";
                ReportViewer1.LocalReport.SetParameters(QueryReportParameter(
                    "查詢日期:" + sBgnDate + "~" + sEndDate,
                    sBuildingName + "用電月報表",
                    sFloor,
                    String.Format("{0:0.####}", dTotalPower),
                    String.Format("{0:0}", iTotalMoney),
                    "寢室"
                    ));
                ReportViewer1.LocalReport.DataSources.Add(new ReportDataSource("ienc_customer_ncku1DataSet", (DataTable)StaticReportDataSet.l_tag_etldata));
                ReportViewer1.LocalReport.DisplayName = "用電月報表";
                UpdatePanel3.Visible = true;
            }
            else
            {
                UpdatePanel3.Visible = false;
                ErrorMsg("該寢室查無資料，請檢視資料！");
                return;
            }
        }

        private void BuildingMonthlyReport(int iBuilding)
        {
            string sBuildingName = ddlBuilding.SelectedItem.Text;   //大樓名稱
            string sBgnDate = tbBgnDate.Text;
            string sEndDate = tbEndDate.Text;
            DateTime dtBgnDate = DateTime.Parse(sBgnDate);
            DateTime dtEndDate = DateTime.Parse(sEndDate);

            if (dtBgnDate > dtEndDate)
            {
                ErrorMsg("查詢的起始時間需大於結束時間！");
                return;
            }

            //查該大樓的所有樓層
            DataTable dtOrgGroupFloor = new DBAccess().getOrgGroupTableByLevel(2);  //取得Level=2的樓層資訊
            IEnumerable<DataRow> queryFloor = from RowFloor in dtOrgGroupFloor.AsEnumerable()
                                              where iBuilding == RowFloor.Field<Int32>("_parent_id")
                                              orderby RowFloor.Field<string>("_name") ascending
                                              select RowFloor;

            decimal dTotalPower = 0;
            Int32 iTotalMoney = 0;
            iEN.Report.ReportDesign.StaticReportDataSet StaticReportDataSet = new ReportDesign.StaticReportDataSet();
            foreach (DataRow RowFloor in queryFloor)
            {
                int iFloor = Convert.ToInt32(RowFloor["_id"].ToString());
                //查該樓層的所有寢室
                DataTable dtOrgGroup = new DBAccess().getOrgGroupTableByLevel(3);  //取得Level=3的寢室資訊
                IEnumerable<DataRow> query = from r in dtOrgGroup.AsEnumerable()
                                             where iFloor == r.Field<Int32>("_parent_id")
                                             select r;
                foreach (DataRow r in query)
                {
                    string sRoomName = r["_name"].ToString().Trim();
                    int iRoom = Convert.ToInt32(r["_id"].ToString());

                    iEN.Report.ReportDesign.StaticReportDataSet.l_tag_etldataRow TempRow = (iEN.Report.ReportDesign.StaticReportDataSet.l_tag_etldataRow)(StaticReportDataSet.l_tag_etldata.NewRow());

                    //查寢室電錶
                    int iElectricMeter = new DBAccess().getElectricMeterByRoom(iRoom);
                    if (iElectricMeter != -1)
                    {
                        //查用電資料
                        DataTable dtFirst = new DBAccess().getTag_etldataTableFirstRecordOfDayByTagID(iElectricMeter, dtBgnDate);   //當月第一筆資料
                        DataTable dtLast = new DBAccess().getTag_etldataTableLastRecordOfDayByTagID(iElectricMeter, dtEndDate);     //當月最後一筆資料
                        if (dtFirst != null && dtLast != null && dtFirst.Rows.Count == 1 && dtLast.Rows.Count == 1)
                        {
                            double dBgnRecord = Convert.ToDouble(dtFirst.Rows[0]["_last"].ToString());      //該月第一筆資料
                            double dEndRecord = Convert.ToDouble(dtLast.Rows[0]["_last"].ToString());       //該月最後一筆資料
                            decimal dPowerCount = (decimal)dEndRecord - (decimal)dBgnRecord;
                            dTotalPower += dPowerCount;
                            string sMoney = String.Format("{0:0}", (dPowerCount * 4) > 0 ? (dPowerCount * 4) : 0);
                            iTotalMoney += Convert.ToInt32(sMoney);

                            TempRow._start_time = Convert.ToDateTime(dtLast.Rows[0]["_start_time"].ToString());
                            TempRow._end_time = Convert.ToDateTime(dtLast.Rows[0]["_end_time"].ToString());
                            TempRow._first = dBgnRecord;
                            TempRow._last = dEndRecord;
                            TempRow._average = String.Format("{0:0.####}", dPowerCount);                    //_average作為使用電度數(度)
                            TempRow._id = Convert.ToInt32(dtLast.Rows[0]["_id"].ToString());
                            TempRow._datetime = sRoomName;                                                  //_datetime用來表示寢室
                            TempRow._device_id = Convert.ToInt32(dtLast.Rows[0]["_device_id"].ToString());
                            TempRow._tag_id = Convert.ToInt32(dtLast.Rows[0]["_tag_id"].ToString());
                            TempRow._count = sMoney;                                                        //_count作為金額
                        }
                        else
                            TempRow._datetime = sRoomName;
                    }
                    else    //該寢室查無電錶資料
                    {
                        TempRow._datetime = sRoomName;
                    }

                    StaticReportDataSet.l_tag_etldata.Addl_tag_etldataRow(TempRow);
                }
            }

            if (StaticReportDataSet.l_tag_etldata.Rows.Count > 0)
            {
                ReportViewer1.Reset();
                ReportViewer1.LocalReport.DataSources.Clear();
                ReportViewer1.LocalReport.ReportPath = "Report\\ReportDesign\\MonthlyReport.rdlc";
                ReportViewer1.LocalReport.SetParameters(QueryReportParameter(
                    "查詢日期:" + sBgnDate + "~" + sEndDate,
                    sBuildingName + "用電月報表",
                    "  ",
                    String.Format("{0:0.####}", dTotalPower),
                    String.Format("{0:0}", iTotalMoney),
                    "寢室"
                    ));
                ReportViewer1.LocalReport.DataSources.Add(new ReportDataSource("ienc_customer_ncku1DataSet", (DataTable)StaticReportDataSet.l_tag_etldata));
                ReportViewer1.LocalReport.DisplayName = "用電月報表";
                UpdatePanel3.Visible = true;
            }
            else
            {
                UpdatePanel3.Visible = false;
                ErrorMsg("該寢室查無資料，請檢視資料！");
                return;
            }
        }

        private ReportParameter[] QueryReportParameter(string sDate, string sReportName, string sRoom, string sTotalPower, string sTotalMoney, string sColumnName)
        {
            ReportParameter[] ReportParameter = new ReportParameter[6];
            ReportParameter[0] = new ReportParameter("Report_Parameter_Date", sDate);
            ReportParameter[1] = new ReportParameter("Report_Parameter_ReportName", sReportName);
            ReportParameter[2] = new ReportParameter("Report_Parameter_Room", sRoom);
            ReportParameter[3] = new ReportParameter("Report_Parameter_TotalPower", sTotalPower);
            ReportParameter[4] = new ReportParameter("Report_Parameter_TotalMoney", sTotalMoney);
            ReportParameter[5] = new ReportParameter("Report_Parameter_Column", sColumnName);
            return ReportParameter;
        }

        private void ErrorMsg(string Msg)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", ";alert('" + Msg + "');", true);
            return;
        }
    }
}